"use client";

import styled from 'styled-components';
import React, { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/router';
import AuthModal from '../components/AuthModal';
import AlertModal from '../components/AlertModal';

import { userScore } from '../utils/request';
import { Containerxx } from './ballStyle'; // 导入样式


const Ball: React.FC = () => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const rulesRef = useRef<HTMLDivElement>(null);
    const animationFrameId = useRef<number>();
    const [showAuthModal, setShowAuthModal] = useState(false);
    const [isLogin, setIsLogin] = useState(false);
    const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
    const [authMode, setAuthMode] = useState<'login' | 'register'>('login');
    const [userId, setUserId] = useState<string | null>(null);
    const [isGame, setIsGame] = useState(false);
    const router = useRouter();

    // 新增 AlertModal 的状态
    const [isAlertOpen, setIsAlertOpen] = useState<boolean>(false);
    const [alertTitle, setAlertTitle] = useState<string>('');
    const [alertMessage, setAlertMessage] = useState<string>('');

    const startTimeoutRef = useRef<number | null>(null);
    const [countdown, setCountdown] = useState<number | null>(null);

    useEffect(() => {
        // 获取登录信息
        const storedToken = localStorage.getItem('token');
        const storedUserInfo = localStorage.getItem('userInfo');
        if (storedToken && storedUserInfo) {
            const userInfo = storedUserInfo ? JSON.parse(storedUserInfo) : null;
            setIsLogin(true);
            setUserId(userInfo.userId);
        } else {
            setIsLogin(false);
        }
    }, []);

    // startGame 函数定义
    const startGame = () => {
        if (!isLogin) {
            setAlertTitle('未登录');
            setAlertMessage('请先登录');
            setIsAlertOpen(true);
            return;
        }
        setIsGame(true);
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        // 游戏变量
        const delay = 500;
        let score = 0;

        // 小球对象
        const ball = {
            x: canvas.width / 2,
            y: canvas.height / 4 * 3,
            r: 10,
            xspeed: 0, // 初始速度设为0
            yspeed: 0, // 初始速度设为0
            speed: 3,
            visible: true,
        };

        // 板子对象
        const paddle = {
            x: canvas.width / 2 - 40,
            y: canvas.height - 20,
            w: 80,
            h: 10,
            speed: 4, // 这里设定球拍的移动速度
            dx: 0,
            visible: true,
        };

        // 随机生成函数，返回 min 和 max 之间的整数
        function getRandomInt(min: number, max: number): number {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

        // 随机生成砖块列数
        const brickRowCount = getRandomInt(5, 10);
        const brickColumnCount = getRandomInt(5, 10); // 列数在3到8之间

        // 计算每个砖块的宽度和间距，使总宽度等于 canvas 宽度减去两边各留 20 的距离
        const canvasWidth = 800;
        const sidePadding = 20;
        const brickPadding = 10;
        const totalPadding = (brickColumnCount - 1) * brickPadding;
        const brickWidth = (canvasWidth - 2 * sidePadding - totalPadding) / brickColumnCount;

        // 随机生成砖块的高度
        const brick = {
            w: brickWidth,
            h: getRandomInt(15, 25), // 高度在15到30像素之间
            padding: brickPadding,
            offsetx: sidePadding,
            offsety: 60,
            visible: true,
        };

        // 创建砖头
        const bricks: { x: number; y: number; w: number; h: number; visible: boolean }[][] = [];

        for (let i = 0; i < brickRowCount; i++) {
            bricks[i] = [];
            for (let j = 0; j < brickColumnCount; j++) {
                const x = j * (brick.w + brick.padding) + brick.offsetx;
                const y = i * (brick.h + brick.padding) + brick.offsety;
                bricks[i][j] = { x, y, ...brick };
            }
        }
        // 画小球
        const drawBall = () => {
            ctx.beginPath();
            ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);
            ctx.fillStyle = ball.visible ? '#0095dd' : 'transparent';
            ctx.fill();
            ctx.closePath();
        };

        // 画板子
        const drawPaddle = () => {
            ctx.beginPath();
            ctx.rect(paddle.x, paddle.y, paddle.w, paddle.h);
            ctx.fillStyle = paddle.visible ? '#0095dd' : 'transparent';
            ctx.fill();
            ctx.closePath();
        };

        // 画砖墙
        const drawBricks = () => {
            bricks.forEach(col => {
                col.forEach(b => {
                    if (b.visible) {
                        ctx.beginPath();
                        ctx.rect(b.x, b.y, b.w, b.h);
                        ctx.fillStyle = '#0095dd';
                        ctx.fill();
                        ctx.closePath();
                    }
                });
            });
        };

        // 画得分栏
        const drawScore = () => {
            ctx.font = '20px Arial';
            ctx.fillStyle = '#000';
            ctx.fillText(`得分: ${score}`, canvas.width - 100, 30);
        };

        // 移动板子
        const movePaddle = () => {
            paddle.x += paddle.dx;

            // 边界检测
            if (paddle.x + paddle.w > canvas.width) {
                paddle.x = canvas.width - paddle.w;
            }

            if (paddle.x < 0) {
                paddle.x = 0;
            }
        };
        let isPaused = false;  // 新增暂停状态
        // 移动小球
        const moveBall = async () => {
            ball.x += ball.xspeed;
            ball.y += ball.yspeed;

            // 墙体碰撞
            if (ball.x + ball.r > canvas.width || ball.x - ball.r < 0) {
                ball.xspeed = -ball.xspeed;
            }
            if (ball.y - ball.r < 0) {
                ball.yspeed = -ball.yspeed;
            }

            // 球板碰撞
            if (
                ball.x > paddle.x &&
                ball.x < paddle.x + paddle.w &&
                ball.y + ball.r > paddle.y
            ) {
                ball.yspeed = -ball.speed;
            }

            // 砖块碰撞
            bricks.forEach(col => {
                col.forEach(b => {
                    if (b.visible) {
                        if (
                            ball.x > b.x &&
                            ball.x < b.x + b.w &&
                            ball.y - ball.r < b.y + b.h &&
                            ball.y + ball.r > b.y
                        ) {
                            ball.yspeed = -ball.yspeed;
                            b.visible = false;
                            increaseScore();
                        }
                    }
                });
            });

            // 撞击到地面
            if (ball.y + ball.r > canvas.height) {
                isPaused = true; // 撞击到地面时暂停游戏
                setIsGame(false);
                ball.visible = false; // 清除小球

                if (animationFrameId.current) {
                    cancelAnimationFrame(animationFrameId.current);
                }

                // 显示暂停提示
                setTimeout(async () => {
                    const storedUserInfo = localStorage.getItem('userInfo');
                    const userInfo = storedUserInfo ? JSON.parse(storedUserInfo) : null;

                    if (userInfo) {
                        const scoreInfo = await userScore({ userId: userInfo.id, score: score });
                        // console.log(scoreInfo);
                    }

                    setAlertTitle('游戏结束');
                    setAlertMessage('您的得分为 ' + score);
                    setIsAlertOpen(true);

                    score = 0;
                }, 100);
            }
        };


        const increaseScore = () => {
            score++;

            if (score % (brickRowCount * brickColumnCount) === 0) {
                ball.visible = false;
                paddle.visible = false;

                setTimeout(() => {
                    showAllBricks();
                    score = 0;
                    paddle.x = canvas.width / 2 - 40;
                    paddle.y = canvas.height - 20;
                    ball.x = canvas.width / 2;
                    ball.y = canvas.height / 2;
                    ball.visible = true;
                    paddle.visible = true;
                }, delay);
            }
        };

        const showAllBricks = () => {
            bricks.forEach(col => {
                col.forEach(b => (b.visible = true));
            });
        };

        const draw = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawBall();
            drawPaddle();
            drawBricks();
            drawScore();
        };

        const update = () => {
            if (isPaused) return;
            moveBall();
            movePaddle();
            draw();
            animationFrameId.current = requestAnimationFrame(update);
        };

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Right' || e.key === 'ArrowRight') {
                paddle.dx = paddle.speed;
            } else if (e.key === 'Left' || e.key === 'ArrowLeft') {
                paddle.dx = -paddle.speed;
            }
        };

        const handleKeyUp = (e: KeyboardEvent) => {
            if (
                e.key === 'Right' ||
                e.key === 'ArrowRight' ||
                e.key === 'Left' ||
                e.key === 'ArrowLeft'
            ) {
                paddle.dx = 0;
            }
        };

        // 添加事件监听
        document.addEventListener('keydown', handleKeyDown);
        document.addEventListener('keyup', handleKeyUp);
        // 生成游戏
        draw();
        // 3秒后开始游戏
        startTimeoutRef.current = window.setTimeout(() => {
            // 设置小球初始速度
            ball.xspeed = Math.random() * 4 - 2; // 随机生成 -2 到 2 之间的水平速度
            ball.yspeed = -2; // 垂直速度始终向上

            update();
            setCountdown(null); // 清除倒计时
        }, 3000);
        setCountdown(3);
        // 清理工作
        return () => {
            if (animationFrameId.current) {
                cancelAnimationFrame(animationFrameId.current);
            }
            if (startTimeoutRef.current) {
                clearTimeout(startTimeoutRef.current);
            }
            document.removeEventListener('keydown', handleKeyDown);
            document.removeEventListener('keyup', handleKeyUp);
        };
    };
    useEffect(() => {
        let countdownInterval: number | null = null;
        if (countdown !== null && countdown > 0) {
            countdownInterval = window.setInterval(() => {
                setCountdown(prev => (prev !== null && prev > 0 ? prev - 1 : null));
            }, 1000);
        }
        return () => {
            if (countdownInterval) {
                clearInterval(countdownInterval);
            }
        };
    }, [countdown]);

    // 显示规则
    const handleShowRules = () => {
        setAlertTitle('规则');
        setAlertMessage('用你的右键和左键移动球拍，使球反弹和打破砖块。如果你漏了球，你的得分和砖块将被重置。');
        setIsAlertOpen(true);
    };

    // 关闭规则
    const handleCloseRules = () => {
        if (rulesRef.current) {
            rulesRef.current.classList.remove('show');
        }
    };

    // 切换下拉菜单
    const toggleDropdown = () => {
        setIsDropdownOpen(prev => !prev);
    };

    // 处理点击“排行榜排名”
    const handleLeaderboard = () => {
        router.push('/list');
    };

    // 处理退出登录
    const handleLogout = () => {
        localStorage.removeItem('token');
        localStorage.removeItem('userId');
        localStorage.removeItem('userInfo');

        setAlertTitle('退出登录');
        setAlertMessage('退出登录成功');
        setIsAlertOpen(true);

        setIsLogin(false);
        setUserId(null);
        window.location.reload();
    };

    // 点击页面其他地方关闭下拉菜单
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            const target = event.target as HTMLElement;
            if (!target.closest('.login-container')) {
                setIsDropdownOpen(false);
            }
        };
        document.addEventListener('click', handleClickOutside);
        return () => {
            document.removeEventListener('click', handleClickOutside);
        };
    }, []);

    const openAuthModal = (mode: 'login' | 'register') => {
        if (isLogin) {
            toggleDropdown();
            return
        }
        setAuthMode(mode);
        setShowAuthModal(true);
    };

    const closeAuthModal = () => {
        setShowAuthModal(false);
    };

    const switchAuthMode = () => {
        setAuthMode(prev => (prev === 'login' ? 'register' : 'login'));
    };

    const handleAlertClose = () => {
        setIsAlertOpen(false);
    };

    return (
        <Containerxx $color={'#B4ADAD'}>
            {/* 登录按钮 */}
            <div className="login-container">
                <button className="btn" onClick={() => openAuthModal('login')}>
                    {isLogin ? userId : '登录'}
                </button>
                {isLogin && (
                    <div className={`dropdown ${isDropdownOpen ? 'show' : ''}`}>
                        <div className="dropdown-item" onClick={handleLeaderboard}>
                            排行榜排名
                        </div>
                        <div className="dropdown-item" onClick={handleLogout}>
                            退出登录
                        </div>
                    </div>
                )}
            </div>

            {/* AuthModal 组件 */}
            <AuthModal
                visible={showAuthModal}
                onClose={closeAuthModal}
                onSwitch={switchAuthMode}
                isLogin={authMode === 'login'}
                setIsLogin={(isLogin) => {
                    setIsLogin(isLogin);
                    if (isLogin) {
                        window.location.reload();
                    }
                }}
            />
            <AlertModal
                isOpen={isAlertOpen}
                title={alertTitle}
                message={alertMessage}
                onClose={handleAlertClose}
            />

            {/* 标题和规则按钮 */}
            <h1>弹球小游戏</h1>
            <div style={{ height: '30px', fontSize: '24px', color: '#fff' }}>
                {countdown && ('游戏将在 ' + countdown + ' 秒后开始,点击右键和左键移动球拍')}
            </div>
            <button className="btn rule-btn" onClick={handleShowRules}>查看规则</button>

            {/* 画布 */}
            <canvas ref={canvasRef} width="800" height="600"></canvas>
            <button className="btn" onClick={startGame} disabled={isGame}>
                开始游戏
            </button>
        </Containerxx>
    );
};

export default Ball;